<template>
  <div class="resume-delivery">
    <div class="section-header">
      <div class="left">
        <h3 class="section-title">简历投递记录</h3>
        <div class="delivery-count">共 {{ totalDeliveries }} 条记录</div>
      </div>
      <div class="right">
        <el-select 
          v-model="statusFilter" 
          placeholder="投递状态" 
          clearable
          class="filter-select"
        >
          <el-option 
            v-for="(label, value) in statusOptions" 
            :key="value"
            :label="label" 
            :value="value" 
          />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          class="date-picker"
        />
      </div>
    </div>
    
    <div class="delivery-list" v-loading="loading">
      <el-table
        :data="filteredDeliveries"
        stripe
        style="width: 100%"
        :empty-text="emptyText"
      >
        <el-table-column prop="jobTitle" label="职位名称" min-width="180">
          <template #default="{ row }">
            <div class="job-info">
              <div class="job-title" @click="viewJobDetail(row.jobId)">
                {{ row.jobTitle }}
              </div>
              <div class="company-name">{{ row.companyName }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="resumeName" label="投递简历" min-width="150">
          <template #default="{ row }">
            <div class="resume-info">
              <el-link 
                type="primary" 
                :underline="false"
                @click="viewResume(row.resumeId)"
              >
                {{ row.resumeName }}
              </el-link>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="deliveryTime" label="投递时间" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.deliveryTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" min-width="120">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)"
              effect="light"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="companyResponse" label="企业反馈" min-width="150">
          <template #default="{ row }">
            <span v-if="row.companyResponse">{{ row.companyResponse }}</span>
            <span v-else class="no-feedback">暂无反馈</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="actions">
              <el-button 
                v-if="canResubmit(row.status)"
                type="primary" 
                link
                @click="resubmitResume(row)"
              >
                重新投递
              </el-button>
              
              <el-button 
                v-if="canViewDetail(row.status)"
                type="primary" 
                link
                @click="viewDeliveryDetail(row)"
              >
                查看详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" v-if="totalDeliveries > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalDeliveries"
        />
      </div>
    </div>
    
    <!-- 投递详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="投递详情"
      width="600px"
      destroy-on-close
    >
      <div v-if="selectedDelivery" class="delivery-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="职位名称">
            {{ selectedDelivery.jobTitle }}
          </el-descriptions-item>
          <el-descriptions-item label="企业名称">
            {{ selectedDelivery.companyName }}
          </el-descriptions-item>
          <el-descriptions-item label="投递简历">
            {{ selectedDelivery.resumeName }}
          </el-descriptions-item>
          <el-descriptions-item label="投递时间">
            {{ formatDate(selectedDelivery.deliveryTime, true) }}
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusType(selectedDelivery.status)">
              {{ getStatusText(selectedDelivery.status) }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item v-if="selectedDelivery.processHistory?.length" label="处理记录">
            <el-timeline>
              <el-timeline-item
                v-for="(history, index) in selectedDelivery.processHistory"
                :key="`history-${index}`"
                :timestamp="formatDate(history.time, true)"
                :type="getTimelineItemType(history.status)"
              >
                {{ history.content }}
              </el-timeline-item>
            </el-timeline>
          </el-descriptions-item>
          
          <el-descriptions-item v-if="selectedDelivery.companyResponse" label="企业反馈">
            {{ selectedDelivery.companyResponse }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            v-if="selectedDelivery && canViewJob(selectedDelivery.status)"
            type="primary"
            @click="viewJobDetail(selectedDelivery.jobId)"
          >
            查看职位
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 状态变量
const loading = ref(false)
const statusFilter = ref('')
const dateRange = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const deliveryList = ref([])
const totalDeliveries = ref(0)

// 投递详情对话框
const detailDialogVisible = ref(false)
const selectedDelivery = ref(null)

// 状态选项
const statusOptions = {
  'submitted': '已投递',
  'viewed': '已查看',
  'interviewing': '面试中',
  'rejected': '不合适',
  'offer': '已录用',
  'expired': '已过期'
}

// 模拟数据
const mockDeliveries = [
  {
    id: 1,
    jobId: 1001,
    jobTitle: '高级前端开发工程师',
    companyName: '字节跳动',
    resumeId: 101,
    resumeName: '互联网技术岗位简历',
    deliveryTime: '2023-05-15 14:30:00',
    status: 'interviewing',
    companyResponse: '通过初筛，已安排一面',
    processHistory: [
      {
        time: '2023-05-15 14:30:00',
        status: 'submitted',
        content: '简历投递成功'
      },
      {
        time: '2023-05-16 10:15:00',
        status: 'viewed',
        content: '简历已被查看'
      },
      {
        time: '2023-05-18 09:23:00',
        status: 'interviewing',
        content: '通过初筛，已安排一面'
      }
    ]
  },
  {
    id: 2,
    jobId: 1002,
    jobTitle: '资深前端工程师',
    companyName: '腾讯科技',
    resumeId: 102,
    resumeName: '互联网技术岗位简历(修订版)',
    deliveryTime: '2023-05-12 09:15:00',
    status: 'rejected',
    companyResponse: '岗位需求变更，暂不招聘',
    processHistory: [
      {
        time: '2023-05-12 09:15:00',
        status: 'submitted',
        content: '简历投递成功'
      },
      {
        time: '2023-05-13 16:45:00',
        status: 'viewed',
        content: '简历已被查看'
      },
      {
        time: '2023-05-14 11:20:00',
        status: 'rejected',
        content: '岗位需求变更，暂不招聘'
      }
    ]
  },
  {
    id: 3,
    jobId: 1003,
    jobTitle: '前端开发工程师',
    companyName: '阿里巴巴',
    resumeId: 101,
    resumeName: '互联网技术岗位简历',
    deliveryTime: '2023-05-10 16:42:00',
    status: 'offer',
    companyResponse: '恭喜你通过所有面试环节，期待你的加入！',
    processHistory: [
      {
        time: '2023-05-10 16:42:00',
        status: 'submitted',
        content: '简历投递成功'
      },
      {
        time: '2023-05-11 09:30:00',
        status: 'viewed',
        content: '简历已被查看'
      },
      {
        time: '2023-05-12 14:00:00',
        status: 'interviewing',
        content: '通过初筛，已安排一面'
      },
      {
        time: '2023-05-14 16:30:00',
        status: 'interviewing',
        content: '一面通过，已安排二面'
      },
      {
        time: '2023-05-16 10:15:00',
        status: 'interviewing',
        content: '二面通过，已安排三面'
      },
      {
        time: '2023-05-18 15:00:00',
        status: 'offer',
        content: '恭喜你通过所有面试环节，期待你的加入！'
      }
    ]
  },
  {
    id: 4,
    jobId: 1004,
    jobTitle: 'Web前端工程师',
    companyName: '百度',
    resumeId: 101,
    resumeName: '互联网技术岗位简历',
    deliveryTime: '2023-05-05 10:30:00',
    status: 'viewed',
    companyResponse: '',
    processHistory: [
      {
        time: '2023-05-05 10:30:00',
        status: 'submitted',
        content: '简历投递成功'
      },
      {
        time: '2023-05-06 14:20:00',
        status: 'viewed',
        content: '简历已被查看'
      }
    ]
  },
  {
    id: 5,
    jobId: 1005,
    jobTitle: '前端开发实习生',
    companyName: '美团',
    resumeId: 103,
    resumeName: '实习生简历',
    deliveryTime: '2023-04-20 11:25:00',
    status: 'expired',
    companyResponse: '',
    processHistory: [
      {
        time: '2023-04-20 11:25:00',
        status: 'submitted',
        content: '简历投递成功'
      },
      {
        time: '2023-05-20 11:25:00',
        status: 'expired',
        content: '简历投递已超过30天，状态已自动更新为已过期'
      }
    ]
  }
]

// 根据状态获取标签类型
const getStatusType = (status) => {
  const statusMap = {
    'submitted': 'info',
    'viewed': 'warning',
    'interviewing': 'success',
    'rejected': 'danger',
    'offer': 'success',
    'expired': ''
  }
  return statusMap[status] || 'info'
}

// 根据状态获取标签文本
const getStatusText = (status) => {
  return statusOptions[status] || '未知状态'
}

// 获取时间线项的类型
const getTimelineItemType = (status) => {
  const typeMap = {
    'submitted': 'primary',
    'viewed': 'info',
    'interviewing': 'warning',
    'rejected': 'danger',
    'offer': 'success',
    'expired': 'info'
  }
  return typeMap[status] || 'primary'
}

// 筛选后的投递记录
const filteredDeliveries = computed(() => {
  let result = [...deliveryList.value]
  
  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value)
  }
  
  // 日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    const start = new Date(startDate)
    const end = new Date(endDate)
    end.setHours(23, 59, 59, 999) // 设置为当天结束时间
    
    result = result.filter(item => {
      const deliveryDate = new Date(item.deliveryTime)
      return deliveryDate >= start && deliveryDate <= end
    })
  }
  
  return result
})

// 空表格提示文本
const emptyText = computed(() => {
  if (statusFilter.value || (dateRange.value && dateRange.value.length === 2)) {
    return '没有符合筛选条件的投递记录'
  }
  return '暂无投递记录'
})

// 格式化日期
const formatDate = (dateString, showTime = false) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  if (showTime) {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  }
  
  return `${year}-${month}-${day}`
}

// 是否可以重新投递
const canResubmit = (status) => {
  return ['rejected', 'expired'].includes(status)
}

// 是否可以查看详情
const canViewDetail = (status) => {
  return true // 所有状态都可以查看详情
}

// 是否可以查看职位
const canViewJob = (status) => {
  return true // 所有状态都可以查看职位
}

// 查看职位详情
const viewJobDetail = (jobId) => {
  detailDialogVisible.value = false
  router.push(`/jobs/${jobId}`)
}

// 查看简历
const viewResume = (resumeId) => {
  router.push(`/resumes/${resumeId}/preview`)
}

// 查看投递详情
const viewDeliveryDetail = (delivery) => {
  selectedDelivery.value = delivery
  detailDialogVisible.value = true
}

// 重新投递简历
const resubmitResume = (delivery) => {
  ElMessageBox.confirm(
    '是否确认重新投递简历？',
    '确认重新投递',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API
    // await resumeApi.resubmitResume(delivery.jobId, delivery.resumeId)
    
    ElMessage.success('简历已重新投递')
    router.push(`/jobs/${delivery.jobId}`)
  }).catch(() => {
    // 用户取消操作
  })
}

// 获取投递记录数据
const fetchDeliveries = async () => {
  loading.value = true
  try {
    // 实际应用中应该从API获取数据
    // const response = await resumeApi.getDeliveries({ page: currentPage.value, pageSize: pageSize.value })
    // deliveryList.value = response.data.items
    // totalDeliveries.value = response.data.total
    
    // 模拟API调用
    setTimeout(() => {
      deliveryList.value = mockDeliveries
      totalDeliveries.value = mockDeliveries.length
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取投递记录失败', error)
    loading.value = false
  }
}

// 监听页码和筛选条件变化
watch([currentPage, pageSize, statusFilter, dateRange], () => {
  fetchDeliveries()
}, { deep: true })

// 初始化
onMounted(() => {
  fetchDeliveries()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.resume-delivery {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-lg;
    
    .left {
      display: flex;
      align-items: baseline;
      
      .section-title {
        font-size: 1.2rem;
        font-weight: 600;
        color: $text-primary;
        margin: 0;
        margin-right: $spacing-sm;
      }
      
      .delivery-count {
        color: $text-secondary;
        font-size: 0.9rem;
      }
    }
    
    .right {
      display: flex;
      gap: $spacing-md;
      
      .filter-select {
        width: 120px;
      }
      
      .date-picker {
        width: 260px;
      }
    }
  }
  
  .delivery-list {
    min-height: 300px;
    
    .job-info {
      .job-title {
        font-weight: 500;
        color: $text-primary;
        margin-bottom: 4px;
        cursor: pointer;
        
        &:hover {
          color: $primary-color;
        }
      }
      
      .company-name {
        font-size: 0.9rem;
        color: $text-secondary;
      }
    }
    
    .resume-info {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .no-feedback {
      color: $text-secondary;
      font-size: 0.9rem;
    }
    
    .actions {
      display: flex;
      gap: $spacing-sm;
    }
    
    .pagination-container {
      margin-top: $spacing-lg;
      display: flex;
      justify-content: center;
    }
  }
  
  .delivery-detail {
    .el-descriptions {
      margin-bottom: $spacing-md;
    }
    
    .el-timeline-item {
      position: relative;
      padding-bottom: $spacing-md;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .resume-delivery {
    .section-header {
      flex-direction: column;
      align-items: flex-start;
      
      .left {
        margin-bottom: $spacing-sm;
      }
      
      .right {
        width: 100%;
        flex-direction: column;
        gap: $spacing-sm;
        
        .filter-select,
        .date-picker {
          width: 100%;
        }
      }
    }
    
    .delivery-list {
      overflow-x: auto;
    }
  }
}
</style> 